from torque.torrent.models import Log, Torrent, OrderedLog

import torque.api.errors as tae

def event(request,hash,description):
    ipaddr = request.META.get('REMOTE_ADDR',None)
    if (ipaddr == None) | (ipaddr == '127.0.0.1'):
        ipaddr = request.META.get('HTTP_X_FORWARDED_FOR',None)
        if ipaddr == None:
            ipaddr = "0.0.0.0"
    
    try:
        torrentObj = Torrent.objects.get(hash = hash)
    except:
        return
    
    try:
        Log.objects.create(torrent_id = torrentObj, user_id = request.user, ip = ipaddr,  action = description)
    except:
        return
		
def getLogs(hash):
	try:
		torrent = Torrent.objects.get(hash = hash)
	except Torrent.DoesNotExist:
		return []
	try:
		logs = OrderedLog.objects.filter(torrent_id = torrent)
	except:
		return []
	
	logList = []
	for log in logs:
		logList.append({'user':str(torrent.user_id),'action':str(log.action),'ip':str(log.ip),'date':str(log.creation)})
	
	return logList
		